<?php

namespace app\api\controller;


use app\common\model\integral\IntegralProductOrderProduct as ProductOrderProduct;
use app\common\model\integral\IntegralProductSpecValue as ProductSpecValue;
use app\common\model\product\UserAddress;
use think\facade\Db;
use think\Request;
use think\Response;

class Integral extends Wap
{


    /**
     * 积分商品
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $calssList = Db::name('customer_integral_product_class')->where('status', 1)->select();
            $data = array();
            $data['class'] = array();
            foreach ($calssList as $i => $v) {
                $data['class'][] = array(
                    'id' => $v['id'],
                    'title' => $v['title'],
                );
            }
            if (isset($post['class_id'])) {
                if ($post['class_id'] > 0) {
                    $goods = Db::name('customer_integral_product_class_bind')->where('class_id', $post['class_id'])->select();

                } else {
                    $goods = Db::name('customer_integral_product_class_bind')->where('class_id', $calssList[0]['id'])->select();
                }
            } else {
                $goods = Db::name('customer_integral_product_class_bind')->where('class_id', $calssList[0]['id'])->select();
            }
            $goods_id = array();
            $list = array();
            foreach ($goods as $i => $v) {
                $goods_id[] = $v['product_id'];
            }
            if (count($goods_id) > 0) {
                $list = Db::name('customer_integral_product')->where('id', 'in', $goods_id)->where('status', 1)->select();
            }

            $data['goods'] = array();
            if (count($list) > 0) {
                foreach ($list as $i => $v) {
                    $data['goods'][] = array(
                        'id' => $v['id'],
                        'title' => $v['name'],
                        'image_url' => $v['cover'],
                        'integral_price' => $v['integral_price'],
                        'price' => $v['price'],
                        'total' => 0,
                    );
                }
            }

            $arr['code'] = 200;
            $arr['data'] = $data;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();

        }
    }

    /**
     * 商品详情
     * @param Request $request
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail(Request $request)
    {
        if (request()->post()) {
            $get = $request->param();
            if (!isset($get['id'])) {
                $arr['code'] = 1001;
                $arr['message'] = '参数错误';
                Response::create($arr, 'json')->send();
                exit();
            }
            $info = Db::name('customer_integral_product')
                ->field('id,name,cover,price,integral_price,sale,intro,covers,service,limit_shop as limit_buy')
                ->where('id', $get['id'])->where('status', 1)
                ->find();
            if (!$info) {
                $arr['code'] = 1001;
                $arr['message'] = '商品已下架';
                Response::create($arr, 'json')->send();
                exit();

            }


            if ($info['limit_buy'] > 0) {
                $user = $this->checkToken();
                $total = ProductOrderProduct::getUserLimitNum($get['id'], $user['id']);
                $info['limit_buy'] = (($info['limit_buy'] - $total) <= 0) ? 0 : $info['limit_buy'] - $total;
            } else {
                $info['limit_buy'] = 9999;
            }


            $info['price'] = $info['price'] * 1;
            $info['integral_price'] = $info['integral_price'] * 1;
            if (!empty($info['covers'])) {
                $info['covers'] = unserialize($info['covers']);
                if (empty($info['covers'])) {
                    $info['covers'][] = $info['cover'];
                }
            } else {
                $info['covers'][] = $info['cover'];
            }
            //sku
            $skuList = Db::name('customer_integral_product_sku')
                ->field('id,price,integral_price,stock,picture,data')
                ->where('product_id', $get['id'])
                ->select();
            $spec = $skuData = $specValueIds = [];
            $info['stock'] = 0;
            foreach ($skuList as $k => $sku) {
                $skuData[$sku['data']] = [
                    'id' => $sku['id'],
                    'integral_price' => $sku['integral_price'] * 1,
                    'price' => $sku['price'] * 1,
                    'img' => $sku['picture'],
                    'stock' => $sku['stock'],
                ];
                $info['stock'] += $sku['stock'];
                $sku['data'] = explode('-', $sku['data']);
                $specValueList = ProductSpecValue::where('id', 'in', $sku['data'])->field('id,title,spec_id')->select()->toArray();
                foreach ($specValueList as $specValue) {
                    if (!isset($spec[$specValue['spec_id']])) {
                        $title = Db::name('customer_integral_product_base_spec')->where('id', $specValue['spec_id'])->value('title');
                        $spec[$specValue['spec_id']]['title'] = $title;
                    }
                    if (!in_array($specValue['id'], $specValueIds)) {
                        $spec[$specValue['spec_id']]['list'][] = [
                            'id' => $specValue['id'],
                            'title' => $specValue['title'],
                        ];
                        $specValueIds[] = $specValue['id'];
                    }
                }
            }
            $info['sku'] = [
                'sku_product' => $skuData,
                'spec' => array_values($spec),
            ];
            unset($info['cover']);
            $arr['code'] = 200;
            $arr['data'] = $info;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();
        }
    }


    /**
     *
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function makeOrder(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();

            $goods = Db::name('customer_integral_product')->where('id', $post['goods_id'])->find();


            $seat = Db::name('customer_integral_product_sku')->where('data', $post['spec'])->find();

            if ($seat['stock'] < 0) {
                $arr['code'] = 1001;
                $arr['message'] = '当前规格库存不足';
                Response::create($arr, 'json')->send();
                exit();
            }
            if ($goods['status'] != 1) {
                $arr['code'] = 1001;
                $arr['message'] = '当前商品已下架';
                Response::create($arr, 'json')->send();
                exit();
            }
            if ($post['address_id'] > 0) {
                $addressModel = UserAddress::where('user_id', $user['id'])->where('id', $post['address_id'])->find();
                $data = array(
                    'order_on' => $this->orderOn(),
                    'user_id' => $user['id'],
                    'integral' => $seat['integral_price'] * $post['num'],
                    'store_id' => $post['store_id'],
                    'order_money' => $seat['price'] * $post['num'],
                    'province_id' => $addressModel['province_id'],
                    'city_id' => $addressModel['city_id'],
                    'area_id' => $addressModel['area_id'],
                    'address_details' => $addressModel['address_details'],
                    'realname' => $addressModel['realname'],
                    'mobile' => $addressModel['mobile'],
                    'goods_id' => $post['goods_id'],
                    'spec' => $post['spec'],
                    'sku_product' => $post['sku_product'],
                    'num' => $post['num'],
                    'create_time' => time(),
                );
            } else {
                $data = array(
                    'order_on' => $this->orderOn(),
                    'user_id' => $user['id'],
                    'integral' => $goods['integral_price'] * $post['num'],
                    'order_money' => $goods['price'] * $post['num'],
                    'goods_id' => $post['goods_id'],
                    'spec' => $post['spec'],
                    'sku_product' => $post['sku_product'],
                    'store_id' => $post['store_id'],
                    'create_time' => time(),
                    'num' => $post['num'],
                );
            }
            if (Db::name('customer_integral_product_order')->insert($data)) {
                $da['order_on'] = $data['order_on'];
                $arr['code'] = 200;
                $arr['data'] = $da;
                $arr['message'] = '获取成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        }
    }


    /**
     * 订单详情
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderDetail(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();

            $order = Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->find();

            $goods = Db::name('customer_integral_product')->where('id', $order['goods_id'])->find();


            $sku = Db::name('customer_integral_product_sku')->where('data', $order['spec'])->find();


            $list = Db::name('mini_room_list')->where('id', $order['store_id'])->find();
            $room = Db::name('coutomer_make')->where('store_id', $order['store_id'])->find();
            // 计算积分
            if ($user['integral'] > 0) {
                if ($user['integral'] >= $sku['integral_price']) {
                    $order['pay_money'] = 0;
                } else {
                    $order['integral'] = $user['integral'];
                    $price = $user['integral'] / $room['integral'];
                    $order['pay_money'] = $order['order_money'] - $price;
                }
            } else {
                $order['pay_money'] = $order['order_money'];
                $order['integral'] = 0;
            }

            Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($order);
            $order['address_lan'] = array();
            if ($order['province_id']) {
                if ($order['province_id']) {
                    $order['province_name'] = Db::name('city')->where('citycode', $order['province_id'])->find();
                }
                if ($order['city_id']) {
                    $order['city_name'] = Db::name('city')->where('citycode', $order['city_id'])->find();
                }
                if ($order['area_id'] > 0) {
                    $order['district_name'] = Db::name('city')->where('citycode', $order['area_id'])->find();
                    if ($order['district_name']) {
                        if ($order['district_name'] == "") {
                            $order['district_name']['name'] = ' ';
                        }
                    }
                } else {
                    $order['district_name']['name'] = ' ';
                }

                $order['address_lan'] = $order['province_name']['name'];
                if (isset($order['province_name']['name'])) {
                    if (isset($order['city_name']['name'])) {
                        $order['address_lan'] = $order['province_name']['name'] . $order['city_name']['name'];

                    }
                    if (isset($order['district_name']['name'])) {
                        $order['address_lan'] = $order['province_name']['name'] . $order['city_name']['name'] . $order['district_name']['name'] . $order['address_details'];

                    }
                }


            }
            $data = array(
                'title' => $goods['name'],
                'order_on' => $order['order_on'],
                'name' => $sku['name'],
                'image_url' => $goods['cover'],
                'integral_price' => $sku['integral_price'],
                'price' => $sku['price'],
                'user_integral' => isset($user['integral']) ? $user['integral'] : 0,
                'pay_money' => $order['pay_money'],
                'room_name' => $list['room_name'],
                'num' => $order['num'],
                'address_lan' => $order['address_lan'],
                'realname' => $order['realname'],
                'province_id' => isset($order['province_id']) ? $order['province_id'] : 0,
                'mobile' => $order['mobile'],
            );
            $arr['code'] = 200;
            $arr['data'] = $data;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();
        }
    }


    /**
     * 修改成功
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateOrder(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();
            $addressModel = UserAddress::where('user_id', $user['id'])->where('id', $post['address_id'])->find();
            $orderData = array(
                'province_id' => $addressModel['province_id'],
                'city_id' => $addressModel['city_id'],
                'area_id' => $addressModel['area_id'],
                'address_details' => $addressModel['address_details'],
                'realname' => $addressModel['realname'],
                'mobile' => $addressModel['mobile'],
                'update_time' => time(),
            );
            if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($orderData)) {
                $arr['code'] = 200;
                $arr['message'] = '修改成功';
                Response::create($arr, 'json')->send();
                exit();
            }

        }
    }


    /**
     * 兑换积分
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addOrder(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();
            $order = Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->find();

            $sku = Db::name('customer_integral_product_sku')->where('data', $order['spec'])->find();
            $order['pay_status'] = 1;
            $order['pay_integral'] = $sku['integral_price'];
            $order['order_status'] = 1;
            $order['status'] = 1;
            if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($order)) {
                $us['integral'] = $user['integral'] - $sku['integral_price'];
                $data = array(
                    'user_id' => $user['id'],
                    'integral' => $sku['integral_price'],
                    'before_integral' => $user['integral'],
                    'after_integral' => $us['integral'],
                    'type' => 1,
                    'store_id' => $order['store_id'],
                    'create_time' => time(),
                    'goods_id' => $order['goods_id'],
                    'order_on' => $order['order_on'],
                );
                Db::name('member')->where('id', $user['id'])->update($us);
                Db::name('mini_user_integral')->insert($data);
                $arr['code'] = 200;

                $arr['message'] = '兑换成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        }

    }

    /**
     * 积分订单
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userOrder(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();

            switch ($post['status']) {

                case 5:
                    $list = Db::name('customer_integral_product_order')->where('user_id', $user['id'])->select();

                    break;
                case 0:
                    $list = Db::name('customer_integral_product_order')->where('status', 0)->where('user_id', $user['id'])->select();

                    break;
                case 1:
                    $list = Db::name('customer_integral_product_order')->where('status', 1)->where('user_id', $user['id'])->select();

                    break;
                case 2:
                    $list = Db::name('customer_integral_product_order')->where('status', 2)->where('user_id', $user['id'])->select();

                    break;
                case 3:
                    $list = Db::name('customer_integral_product_order')->where('status', 3)->where('user_id', $user['id'])->select();

                    break;
                case 4:
                    $list = Db::name('customer_integral_product_order')->where('status', 4)->where('user_id', $user['id'])->select();

                    break;
                case 6:
                    $list = Db::name('customer_integral_product_order')->where('status', 6)->where('user_id', $user['id'])->select();

                    break;
            }
            $data = array();
            foreach ($list as $i => $v) {

                $goods = Db::name('customer_integral_product')->where('id', $v['goods_id'])->find();

                $sku = Db::name('customer_integral_product_sku')->where('data', $v['spec'])->find();

                $store = Db::name('mini_room_list')->where('id', $v['store_id'])->find();
                $data[] = array(
                    'store_name' => $store['room_name'],
                    'order_on' => $v['order_on'],
                    'status' => $v['status'],
                    'title' => $goods['name'],
                    'integral_price' => $sku['integral_price'],
                    'price' => $sku['price'],
                    'image_url' => $goods['cover'],
                    'num' => $v['num'],
                    'heal_url' => get_image_url($store['head_url']),
                );
            }
            $arr['code'] = 200;
            $arr['data'] = $data;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();
        }
    }


    /**
     * 取消订单
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();

            $order = Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->find();
            if ($order['status'] == 1) {
                $mark['mark'] = 0;
                if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($mark)) {
                    $arr['code'] = 200;
                    $arr['message'] = '取消成功';
                    Response::create($arr, 'json')->send();
                    exit();
                }
            } else {
                if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->delete()) {
                    $arr['code'] = 200;

                    $arr['message'] = '取消成功';
                    Response::create($arr, 'json')->send();
                    exit();
                }
            }

        }
    }

    /**
     * 申请退款
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refund(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();
            $order = Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->find();
            if ($order['status'] > 2) {
                $arr['code'] = 101;

                $arr['message'] = '不可重复申请';
                Response::create($arr, 'json')->send();
                exit();
            }
            $da['status'] = 6;
            if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($da)) {
                $arr['code'] = 200;

                $arr['message'] = '申请成功。商家审核中';
                Response::create($arr, 'json')->send();
                exit();
            }
        }
    }

    /**
     * 确认收货
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receipt(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();
            $user = $this->checkToken();
            $order = Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->find();
            if ($order['status'] != 2) {
                $arr['code'] = 101;

                $arr['message'] = '当前状态不可确认收货';
                Response::create($arr, 'json')->send();
                exit();
            }
            $da['status'] = 4;
            if (Db::name('customer_integral_product_order')->where('order_on', $post['order_on'])->update($da)) {
                $arr['code'] = 200;

                $arr['message'] = '收货成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        }
    }
}